//
//  ChargeViewController.m
//  DaDaBao
//
//  Created by user on 15/8/20.
//  Copyright (c) 2015年 User. All rights reserved.
//
#import "SuccessViewController.h"
#import "AppDelegate.h"
#import "Order.h"
#import "CardManageModel.h"
#import "ChargeViewController.h"
#import "SecureViewController.h"
#import "APay.h"


@interface ChargeViewController ()<UIAlertViewDelegate,APayDelegate>
@property (nonatomic,strong) UITextField * chargeTextField;

@property (nonatomic, assign) int idx;
@end

@implementation ChargeViewController


#pragma mark alertDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag == 100)
    {
        [AppGlobalClass exitLogin];
        
        LoginViewController *loginViewCon = [[LoginViewController alloc]init];
        [self presentViewController:loginViewCon animated:TRUE completion:^{}];
        
        NSArray *listArray = self.navigationController.viewControllers;
        
        id tabBar = [listArray objectAtIndex:1];
        if([[tabBar class] isSubclassOfClass:[UITabBarController class]])
        {
            UITabBarController *tabBarCon = tabBar;
            tabBarCon.selectedIndex = 0;
            [self.navigationController popToViewController:[listArray objectAtIndex:1] animated:TRUE];
        }
        else
        {
            UITabBarController *tabBarCon = [listArray objectAtIndex:2];
            tabBarCon.selectedIndex = 0;
            [self.navigationController popToViewController:[listArray objectAtIndex:2] animated:TRUE];
        }
    }
    if(alertView.tag == 101)
    {
        [self.navigationController popViewControllerAnimated:TRUE];
    }
    if (alertView.tag == 10000) {
        switch (buttonIndex) {
            case 0:
                break;
            case 1:
            {
                SecureViewController * vc = [[SecureViewController alloc]init];
                [self.navigationController pushViewController:vc animated:TRUE];
            }
                break;

            default:
                break;
        }
    }
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:TRUE];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloginView) name:@"reLogin" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{

    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];
    [self createUI];
    
    [AppGlobalClass PostDataWithNSstring:CHECK_CHARGE_URL withDictionary:nil success:^(NSDictionary *dictionary){
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:FALSE]])
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:[dictionary objectForKey:@"message"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alert setTag:101];
            [alert show];
        }
        
    } failure:^(NSError *error){
    } networkerror:^(NSString *networkerror)
     {
     }];
}
-(void)reloginView
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"登录失败，请重新登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert setTag:100];
    [alert show];
}

#pragma mark ------------创建导航栏
-(void)createUI
{
    [[UIApplication sharedApplication]setStatusBarHidden:FALSE];
    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
    
    TopView *topView =[[TopView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"充值"];
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0.0f, 20.0f, 64.0f, 44.0f)];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(buttonBackTapped:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:backBtn];
    [self.view addSubview:topView];
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 64.0f+20.0f, SCREEN_WIDTH, 50.0f)];
    bgView.backgroundColor = [UIColor whiteColor];
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 15.0f,50.0f, 20.0f)];
    lab.text = @"金额";
    [bgView addSubview:lab];
    
    _chargeTextField = [[UITextField alloc] initWithFrame:CGRectMake(lab.frame.origin.x+lab.frame.size.width+10.0f, 18.0f, 200.0f, 20.0f)];
    _chargeTextField.keyboardType = UIKeyboardTypeDecimalPad;
    _chargeTextField.placeholder =@"请输入充值金额";
    [_chargeTextField setValue:[UIFont boldSystemFontOfSize:14.0f] forKeyPath:@"_placeholderLabel.font"];

    [bgView addSubview:_chargeTextField];
    
    [self.view addSubview:bgView];

    UIButton * chargeBtn = [[UIButton alloc]initWithFrame:CGRectMake(15.0f, bgView.frame.size.height+bgView.frame.origin.y+50.0f, SCREEN_WIDTH-30.0f, 35.0f*HSCALE)];
    chargeBtn.backgroundColor = [UIColor hexStringToColor:RED_COLOR_VALUE];
    chargeBtn.layer.cornerRadius = 5;
    chargeBtn.layer.masksToBounds = TRUE;
    [chargeBtn setTitle:@"充 值" forState:UIControlStateNormal];
    [chargeBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:20]];
    [chargeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [chargeBtn addTarget:self action:@selector(buttonGoToChargeNextViewController:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:chargeBtn];
}

#pragma mark-返回方法
-(void)buttonBackTapped:(id)sender
{
    [self.navigationController popViewControllerAnimated:TRUE];
}
-(void)buttonGoToChargeNextViewController:(id)sender
{
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"idCardVStatus"] isEqualToNumber:[NSNumber numberWithInt:0]]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您尚未进行实名认证，是否进行实名认证？" delegate:self cancelButtonTitle:@"不，谢谢" otherButtonTitles:@"立刻认证", nil];
        alert.tag = 10000;
        [alert show];
        return;
    }
    if (_chargeTextField.text.length <=0 )
    {
        ALERT_VIEW(@"请输入金额");
        return;
    }    if ([_chargeTextField.text doubleValue]>999999999) {
        ALERT_VIEW(@"金额过大");
        return;
    }

    [self.view endEditing:TRUE];//键盘下去
    [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];
    
    NSString * token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
    
    [AppGlobalClass PostDataWithNSstring:GETPAYDATA withDictionary:@{@"token":token,@"money":_chargeTextField.text} success:^(NSDictionary *dictionary) {
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
           
            //获取支付所需信息
            NSDictionary * mdict = [[[[dictionary objectForKey:@"responseData"]firstObject]objectForKey:@"rows"] firstObject];
            NSString * inputCharset = [NSString stringWithFormat:@"%@",[mdict objectForKey:@"inputCharset"]];
            NSString * merchantId = [NSString stringWithFormat:@"%@",[mdict objectForKey:@"merchantId"]];
            NSString * orderCurrency = [NSString stringWithFormat:@"%@",[mdict objectForKey:@"orderCurrency"]];
            NSString * orderDatetime = [NSString stringWithFormat:@"%@",[mdict objectForKey:@"orderDatetime"]];
            NSString * orderNo = [NSString stringWithFormat:@"%@",[mdict objectForKey:@"orderNo"]];
            NSString * payType = [NSString stringWithFormat:@"%@",[mdict objectForKey:@"payType"]];
            NSString * productName = [NSString stringWithFormat:@"%@",[mdict objectForKey:@"productName"]];
            NSString * receiveUrl = [NSString stringWithFormat:@"%@",[mdict objectForKey:@"receiveUrl"]];
            NSString * signType = [NSString stringWithFormat:@"%@",[mdict objectForKey:@"signType"]];
            NSString * version = [NSString stringWithFormat:@"%@",[mdict objectForKey:@"version"]];
            NSString * key = [NSString stringWithFormat:@"%@",[mdict objectForKey:@"key"]];
            NSString * orderAmount = [NSString stringWithFormat:@"%@",[mdict objectForKey:@"orderAmount"]];
            NSArray * paaArray = @[
                                 
                                 ////协议字符集 1-UTF-8  2-GBK; 3-GB2312
                                 inputCharset, @"inputCharset",
                                 
                                 //支付通知结果以此为准,后台通知商户网站支付结 果的 url 地址
                                 receiveUrl, @"receiveUrl",
                                 ////协议版本,固定填 v1.0
                                 version, @"version",
                                 //订单信息签名方式
                                 signType, @"signType",
                                 
                                 //通联分配给商户的ID
                                 merchantId, @"merchantId",
                                 //商户当前支付订单号
                                 orderNo, @"orderNo",
                                 orderAmount, @"orderAmount",
                                 orderCurrency, @"orderCurrency",
                                 orderDatetime, @"orderDatetime",
                                 
                                 //商品名称
                                 productName, @"productName",
                                 //27-移动(跨境)支付 v2.x版本的支付控件
                                 payType, @"payType",
                                 
                                 //商户订单签名key
                                 //在通联商户平台维护
                                 key, @"key",
                                 ];
            NSString * orderString = [self formatPaa:paaArray];
            [APay startPay:orderString viewController:self delegate:self mode:@"01"];
        }
        else
        {
            ALERT_VIEW([dictionary objectForKey:@"message"]);
        }
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
    } networkerror:^(NSString *networkerror) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
    }];
   
}
- (void)APayResult:(NSString *)result {
    
    NSLog(@"%@", result);
    NSArray *parts = [result componentsSeparatedByString:@"="];
    NSError *error;
    NSData *data = [[parts lastObject] dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    NSInteger payResult = [dic[@"payResult"] integerValue];
    NSString *format_string = @"支付结果::支付%@";
    if (payResult == APayResultSuccess) {
        NSLog(format_string,@"成功");
    } else if (payResult == APayResultFail) {
        NSLog(format_string,@"失败");
    } else if (payResult == APayResultCancel) {
        NSLog(format_string,@"取消");
    }
}
#pragma mark--------------签名格式化

-(NSString *)formatPaa:(NSArray *)array {
    
    NSMutableDictionary *mdic = [NSMutableDictionary dictionary];
    
    NSMutableString *paaStr = [[NSMutableString alloc] init];
    for (int i = 0; i < array.count; i++) {
        [paaStr appendFormat:@"%@=%@&", array[i+1], array[i]];
        mdic[array[i+1]] = array[i];
        i++;
    }
    
    NSString *signMsg = [self md5:[paaStr substringToIndex:paaStr.length - 1]];
    mdic[@"signMsg"] = signMsg.uppercaseString;
    
    if (mdic[@"key"]) {//商户私有签名密钥 通联后台持有不传入插件
        [mdic removeObjectForKey:@"key"];
    }
    
    NSError *error;
    NSData *data = [NSJSONSerialization dataWithJSONObject:mdic options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonStr = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
    
    [paaStr setString:jsonStr];
    
    return paaStr;
}

//计算订单签名信息
//签名串的顺序与范例
/**
 
 inputCharset=1&receiveUrl=http://www&version=v1.0&signType=1&merchantId=100020091218001&orderNo=201505111408570000&orderAmount=3500&orderCurrency=0&orderDatetime=20150511140857&productName=二维码&ext1=<USER>201410131001556</USER>&payType=27&key=1234567890
 
 **/

//计算字符串对应的md5值
-(NSString *)md5:(NSString *)string {
    
    NSLog(@"%@", string);
    
    if (string == nil) { return nil; }
    
    const char *str = [string cStringUsingEncoding:NSUTF8StringEncoding];
    CC_LONG strLen = (CC_LONG)[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
    unsigned char *result = calloc(CC_MD5_DIGEST_LENGTH, sizeof(unsigned char));
    CC_MD5(str, strLen, result);
    
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; ++i) {
        [hash appendFormat:@"%02x", result[i]];
    }
    
    free(result);
    
    return hash;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:TRUE];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
